import type { PropsInterface } from './types/props'
import { getCurrentInstance } from 'vue'
export function useDarwer(props: PropsInterface) {
  // 加载状态
  const isLoading = ref(false)
  // emit
  const { emit } = getCurrentInstance()
  /**
   * 处理提交的
   */
  const useBeforeChange = () => {
    return new Promise<void>((resolve, reject) => {
      const isFunction = Object.prototype.toString.call(props.beforeChange) === '[object Function]'
      if (!isFunction) {
        reject()
        return
      }

      props.beforeChange &&
        props
          .beforeChange()
          .then(() => {
            useClosed()
            emit('ok')
            resolve()
          })
          .catch(() => {
            reject()
          })
    })
  }
  /**
   * 关闭
   */
  const useClosed = () => {
    emit('update:open', false)
  }
  // 处理加载逻辑
  const useInnerLoading = () => {
    const isFunction = Object.prototype.toString.call(props.innerLoading) === '[object Function]'
    if (!isFunction) {
      return
    }
    isLoading.value = true
    props.innerLoading &&
      props
        .innerLoading()
        .then(() => {
          isLoading.value = false
        })
        .catch(() => {
          isLoading.value = false
        })
  }

  return {
    isLoading,
    useClosed,
    useInnerLoading,
    useBeforeChange,
  }
}
